package com.cn.ZhiKeDianShang.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.cn.ZhiKeDianShang.AppConfig;
import com.cn.ZhiKeDianShang.BuildConfig;
import com.cn.ZhiKeDianShang.MainActivity;
import com.cn.ZhiKeDianShang.R;
import com.cn.ZhiKeDianShang.base.BaseFragment;
import com.cn.ZhiKeDianShang.model.CheckUpdateBean;
import com.cn.ZhiKeDianShang.model.response.MyInfoBean;
import com.cn.ZhiKeDianShang.model.response.MyServiceBean;
import com.cn.ZhiKeDianShang.presenter.MineFragmentPresenter;
import com.cn.ZhiKeDianShang.presenter.view.MineFragmentView;
import com.cn.ZhiKeDianShang.ui.activity.LoginActivity;
import com.cn.ZhiKeDianShang.ui.activity.MyWebView;
import com.cn.ZhiKeDianShang.ui.activity.UpdateInfoActivity;
import com.cn.ZhiKeDianShang.ui.activity.UpdatePhoneActivity;
import com.cn.ZhiKeDianShang.ui.activity.UpdatePwdActivity;
import com.cn.ZhiKeDianShang.util.ActivityManager;
import com.cn.ZhiKeDianShang.util.AndroidUtil;
import com.cn.ZhiKeDianShang.util.ClipboardUtils;
import com.cn.ZhiKeDianShang.util.PrefShare;
import com.cn.ZhiKeDianShang.util.ProgressDialogFragment;
import com.cn.ZhiKeDianShang.util.ToastUtil;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.HttpUtils;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.ObjectResult;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.Result;
import com.hailong.appupdate.AppUpdateManager;
import com.makeramen.roundedimageview.RoundedImageView;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;

/**
 * 我的
 * Created by chengaofu on 2017/6/21.
 */

public class MineFragment extends BaseFragment<MineFragmentView, MineFragmentPresenter> implements MineFragmentView {


    @BindView(R.id.im_image)
    RoundedImageView imImage;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.tv_guanlima)
    TextView tvGuanlima;
    @BindView(R.id.tv_inviteurl)
    TextView tvInviteurl;
    @BindView(R.id.tv_code)
    TextView tv_code;

    Unbinder unbinder;
    private ProgressDialogFragment mProgressDialog;


    @Override
    protected void initViewsAndEvents() {

    }

    private void supportRequestWindowFeature(int featureActionBarOverlay) {
    }


    /**
     * @param
     */
    private void getInfo() {
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        HttpUtils.post().url(AppConfig.USER_INDEX)
                .params(params)
                .addSecret()
                .build()
                .execute(new BaseCallback<MyInfoBean>(MyInfoBean.class) {
                    @Override
                    public void onResponse(ObjectResult<MyInfoBean> result) {
//                        DialogHelper.dismissProgressDialog();
                        Log.d("Debug", "到达请求这里---");
                        if (Result.checkSuccess(getActivity(), result)) {
                            MyInfoBean data = result.getData();
                            Glide.with(getActivity())
                                    .load(data.getUserinfo().getAvatar())
                                    .into(imImage);
                            tvNickname.setText(data.getUserinfo().getNickname());
                            tvUsername.setText(data.getUserinfo().getUsername());
                            tvGuanlima.setText(data.getUserinfo().getAssociationcode() + "");
                            tvInviteurl.setText(data.getUserinfo().getInvitationlink() + "");
                            tv_code.setText("V"+ BuildConfig.VERSION_NAME);
                            PrefShare.getInstance(getActivity()).saveString("nickname", data.getUserinfo().getNickname());
                            PrefShare.getInstance(getActivity()).saveString("avatar", data.getUserinfo().getAvatar() + "");
                            PrefShare.getInstance(getActivity()).saveString("provincename", data.getUserinfo().getProvincename());
                            PrefShare.getInstance(getActivity()).saveString("cityname", data.getUserinfo().getCityname() + "");
                            PrefShare.getInstance(getActivity()).saveString("province", data.getUserinfo().getProvince());
                            PrefShare.getInstance(getActivity()).saveString("city", data.getUserinfo().getCity() + "");
                            PrefShare.getInstance(getActivity()).saveString("gender", data.getUserinfo().getGender() + "");

                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    /**
     * @param
     */
    private void getServices() {
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        HttpUtils.post().url(AppConfig.USER_CONTACT)
                .params(params)
                .build()
                .execute(new BaseCallback<MyServiceBean>(MyServiceBean.class) {
                    @Override
                    public void onResponse(ObjectResult<MyServiceBean> result) {
//                        DialogHelper.dismissProgressDialog();
                        Log.d("Debug", "到达请求这里---");
                        if (Result.checkSuccess(getActivity(), result)) {
                            Intent intent = new Intent(getActivity(), MyWebView.class);
                            intent.putExtra("url", result.getData().getUrl());
                            intent.putExtra("title", "联系客服");
                            startActivity(intent);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    /**
     * @param
     */
    private void logout() {
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        HttpUtils.post().url(AppConfig.USER_LOGOUT)
                .params(params)
                .build()
                .execute(new BaseCallback<MyServiceBean>(MyServiceBean.class) {
                    @Override
                    public void onResponse(ObjectResult<MyServiceBean> result) {
//                        DialogHelper.dismissProgressDialog();
                        Log.d("Debug", "到达请求这里---");
                        if (Result.checkSuccess(getActivity(), result)) {
                            PrefShare.getInstance(getActivity()).saveString("token", "");
                            PrefShare.getInstance(getActivity()).saveString("userId", "");
                            PrefShare.getInstance(getActivity()).saveString("nickname", "");
                            PrefShare.getInstance(getActivity()).saveString("avatar", "");
                            PrefShare.getInstance(getActivity()).saveString("provincename", "");
                            PrefShare.getInstance(getActivity()).saveString("cityname", "");
                            if (getActivity() != null) {
                                startActivity(new Intent(getActivity(), LoginActivity.class));
                                ActivityManager.getInstance().finishActivity(MainActivity.class);
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    @Override
    public void onResume() {
        super.onResume();
        getInfo();
    }

    @Override
    protected int getErrorLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected int getNormalLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected MineFragmentPresenter createPresenter() {
        return new MineFragmentPresenter(getContext(), this);
    }


    @Override
    public void requestFailed(String message) {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

    }

    @OnClick({R.id.ll_updateinfo, R.id.rl_updatepwd, R.id.rl_update, R.id.rl_services, R.id.rl_updatephone, R.id.tv_guanlian_copefuz, R.id.rl_guanlian, R.id.tv_inviteurl_copefuz, R.id.rl_inviteurl, R.id.rl_loginout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_updateinfo:
                startActivity(new Intent(getActivity(), UpdateInfoActivity.class));
                break;
            case R.id.rl_updatepwd:
                startActivity(new Intent(getActivity(), UpdatePwdActivity.class));
                break;
            case R.id.rl_updatephone:
                startActivity(new Intent(getActivity(), UpdatePhoneActivity.class));
                break;
            case R.id.tv_guanlian_copefuz:
                ClipboardUtils.setClipboard(getActivity(), tvGuanlima.getText().toString(), "关联码复制成功");
                break;
            case R.id.rl_guanlian:
                break;
            case R.id.tv_inviteurl_copefuz:
                ClipboardUtils.setClipboard(getActivity(), tvInviteurl.getText().toString(), "邀请链接复制成功");

                break;
            case R.id.rl_inviteurl:
                break;
            case R.id.rl_update:
                checkUpdate();
                break;
            case R.id.rl_services:
                getServices();
                break;
            case R.id.rl_loginout:
                logout();
                break;
        }
    }


    /**
     * @param
     */
    private void checkUpdate() {
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        HttpUtils.post().url(AppConfig.COMMON_VERSION)
                .params(params)
                .build()
                .execute(new BaseCallback<CheckUpdateBean>(CheckUpdateBean.class) {
                    @Override
                    public void onResponse(ObjectResult<CheckUpdateBean> result) {
//                        DialogHelper.dismissProgressDialog();
                        Log.d("Debug", "到达请求这里---");
                        if (Result.checkSuccess(getActivity(), result)) {
                            CheckUpdateBean data = result.getData();
                            String currentVersion = BuildConfig.VERSION_NAME;
                            if (data != null) {
                                //当前版本小于 线上版本  提示更新
                                if (AndroidUtil.compareVersion(currentVersion, data.getAndroidNewVersion()) < 0) {
                                    String arr[] = new String[1];
                                    arr[0] = data.getAndroidUpdateDescription();
                                    AppUpdateManager.Builder builder = new AppUpdateManager.Builder(getActivity());
                                    builder.apkUrl(data.getApkUrl())
                                            .updateContent(arr)
                                            .updateForce(false)
                                            .build();
                                } else {
                                    ToastUtil.showShort("当前版本是最新版本");
                                }
                            }

                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }

}